home *** CD-ROM | disk | FTP | other *** search
- Path: news1.h1.usa.pipeline.com!usenet
- From: grantp@usa.pipeline.com(Pete)
- Newsgroups: comp.lang.c++
- Subject: Re: Yet a question about random
- Date: 26 Feb 1996 00:35:58 GMT
- Organization: Kalevi, Inc.
- Message-ID: <4gqv9e$q80@news1.usa.pipeline.com>
- NNTP-Posting-Host: pipe11.h1.usa.pipeline.com
- X-PipeUser: grantp
- X-PipeHub: usa.pipeline.com
- X-PipeGCOS: (Pete)
- X-Newsreader: Pipeline USA v3.3.0
-
- On Feb 25, 1996 12:47:24 in article <Yet a question about random>,
- 'm151843@proffa.cc.tut.fi (Edvard Majakari)' wrote:
-
-
- >I use the following function to produce (pseudo)random numbers
- >between 1...top. However, this algorithm seems to be far from
- >good pseudorandom. But the hint was in rand manpage - any good
- >ideas to produce better 'random' numbers?
- >
- >-----&<------------------------&<-------------------------------
- >
- >#include <stdlib.h>
- >#include <sys/time.h>
- >#include <unistd.h>
- >
- >int randomize(float top) {
- > int rnum;
- > timeval seed; //see struct timeval for further details
- > gettimeofday(&seed, NULL);
- > srand(seed.tv_usec); //initialize with millisecs
- > rnum = 1+(int) (top*rand()/(RAND_MAX+1.0));
- > return rnum;
- >}
- Two things:
-
- First, you should call srand() only once in your program.
- Reinitializing the random number generator each time rand()
- is called is not likely to produce a good distribution.
-
- Second, I'm not quite sure what the desired result is. Is it
- an integer in the set (1, top)? If so, just use the remainder
- operator:
-
- return (rand() % (int)top) + 1;
-
-
- --
- Pete Grant
- Kalevi, Inc.
- Software Engineering & development
-